package com.quanyan.club.service.impl;

import baidu.webapi.impl.BaiduLBS;
import baidu.webapi.model.AddressComponent;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.quanyan.activity.entity.ActivityDesc;
import com.quanyan.activity.entity.ActivityMedia;
import com.quanyan.activity.response.RespActivityPoster;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.*;
import com.quanyan.club.entity.vo.resp.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.pullclub.service.PullClubSupportService;
import com.quanyan.club.service.*;
import com.quanyan.club.util.ActivityUtils;
import com.quanyan.comment.constants.UserCenterConstants;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.comment.reqeust.ReqCommentDetailScore;
import com.quanyan.comment.reqeust.ReqCommentQuery;
import com.quanyan.comment.reqeust.ReqIsComment;
import com.quanyan.comment.reqeust.ReqUserCollectQuery;
import com.quanyan.comment.response.RespCommentTagAndCommentDetail;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.comment.serviceFacade.UserCollectServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.search.service.ActivitySearchService;
import com.quanyan.search.service.impl.ActivitySearchServiceImpl;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by yue.yuan on 2016/11/30.
 */
@Service("activityCRUDService")
public class ActivityCRUDServiceImpl extends BaseServiceImpl implements ActivityCRUDService{

    private static final Logger logger = LoggerFactory.getLogger(ClubActivityServiceImpl.class);
    private final String REGIST_ACTIVITY = "REGIST_ACTIVITY";
    private final String POST_ACTIVITY = "POST_ACTIVITY";
    private final String EVALUATION_ACTIVITY = "EVALUATION_ACTIVITY";

    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;
    @Autowired
    private TbClubMapper tbClubMapper;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private CommentServiceFacade commentServiceFacade;
    @Autowired
    private UserCollectServiceFacade userCollectServiceFacade;
    @Autowired
    private TbActivityPosterMapper tbActivityPosterMapper;
    @Autowired
    private ClubCommentService clubCommentService;
    @Autowired
    private TbDistrictMapper tbDistrictMapper;
    @Autowired
    private TbCityMapper tbCityMapper;
    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private TbActivityDescMapper tbActivityDescMapper;
    @Autowired
    private TbActivityMultimediaMapper tbActivityMultimediaMapper;
    @Autowired
    private ClubActivityCRUDMapper clubActivityCRUDMapper;
    @Autowired
    private ActivitySupportService activitySupportService;
    @Autowired
    private ActivityAccountService activityAccountService;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<RespCreateClubActivity> saveActivity(ReqClubActivity reqClubActivity) {

        //创建活动校验参数
        validSaveActivityRequest(reqClubActivity);
        //校验俱乐部
        TbClub tbClub = tbClubMapper.selectByPrimaryKey(reqClubActivity.getClubId());
        if(tbClub.getIsDelete().equals(Constants.BYTE_ONE))
        {
            throw new BizException("此俱乐部已经被暂停不能发布活动");
        }
        //保存俱乐部活动
        TbClubActivity tbClubActivity = new TbClubActivity();
        TbActivity tbActivity = new TbActivity();
        TbActivityPoster tbActivityPoster = new TbActivityPoster();
        TbActivityDesc tbActivityDesc = new TbActivityDesc();
        List<TbActivityMultimedia> tbActivityMultimedias = new ArrayList<TbActivityMultimedia>();
        //地址校准
        PlaceDubboProvider place = null;
        String activitySite = null;
        if(null != reqClubActivity.getPlaceId() && reqClubActivity.getPlaceId() > 0)
        {
            place = activitySupportService.getActivityPlace(reqClubActivity.getPlaceId());
            if(null == place)
            {
                throw new BizException("获取不到场馆的城市区域呀！");
            }
            reqClubActivity.setCityId(place.getCityId());
            reqClubActivity.setDistrictId(place.getDistrictId());
            activitySite = place.getName();
        }else {
            Double lat = reqClubActivity.getLat();
            Double lng = reqClubActivity.getLng();
            BaiduLBS lbs = new BaiduLBS();
            AddressComponent addressComponent =
                    lbs.getAddressComponentByLatAndLng(lat, lng);
            logger.warn("addressComponent" + JSONObject.toJSONString(addressComponent));
            tbClubActivity.setLat(lat);
            tbClubActivity.setLng(lng);
            TbCityExample cityExample = new TbCityExample();
            String cityName = addressComponent.getCity();
            cityName = cityName.substring(0, cityName.length()-1);
            cityExample.createCriteria().andNameLike(cityName + "%");
            List<TbCity> cities = tbCityMapper.selectByExample(cityExample);
            if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(cities))
            {
                logger.warn("活动地点信息：" + JSONObject.toJSONString(reqClubActivity));
                throw new BizException("你所选的地址无法使用，请联系工作人员");
            }
            if (null != cities && cities.size() == 1) {
                TbCity city = cities.get(0);
                tbClubActivity.setCityId(city.getId());
                reqClubActivity.setCityId(city.getId());
                TbDistrictExample districtExample = new TbDistrictExample();
                districtExample.createCriteria()
                        .andNameLike(addressComponent.getDistrict())
                        .andCityIdEqualTo(city.getId());
                List<TbDistrict> districts =
                        tbDistrictMapper.selectByExample(districtExample);
                logger.warn("通过经纬度查询到城市：" + JSONObject.toJSONString(city) +
                        "区域：" + JSONObject.toJSONString(districts));
                if (null != districts && districts.size() == 1) {
                    TbDistrict district = districts.get(0);
                    tbClubActivity.setDistrictId(district.getId());
                    reqClubActivity.setDistrictId(district.getId());
                }
            }
            activitySite = reqClubActivity.getPlaceAddress();
        }
        //包装
        convertActivityReqToDb(reqClubActivity, tbClubActivity, tbActivity,
                tbActivityPoster, tbActivityDesc,tbActivityMultimedias, 1);
        tbClubActivityMapper.insertSelective(tbClubActivity);
        tbActivityDescMapper.insertSelective(tbActivityDesc);
        if(null != tbActivityMultimedias && tbActivityMultimedias.size() > 0)
        {
            clubActivityCRUDMapper.batchInsertMedia(tbActivityMultimedias);
        }
        RespClubActivity respClubActivity = selectClubActivityById(tbClubActivity.getActivityId());
        int count = clubActivityCRUDMapper.firstActivity(tbClub.getUid());
        logger.warn("已创建活动数:" + count);
        activitySupportService.afterSaveActivity(respClubActivity, tbClub, count == 1);
        RespCreateClubActivity resp = new RespCreateClubActivity();
        int clubId = tbClubActivity.getClubId();
        int activityId = tbClubActivity.getActivityId();
        resp.setClubId(tbClubActivity.getClubId());
        resp.setActivityId(tbClubActivity.getActivityId());
        resp.setLogoUrl(tbClub.getLogoUrl());
        resp.setName(tbActivity.getName());
        resp.setActivitySite(activitySite);
        return APIResponse.returnSuccess(resp);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<RespClubActivity> updateActivity(ReqClubActivity reqClubActivity) {
        if (null == reqClubActivity.getId() && null != reqClubActivity.getActivityId()) {
            reqClubActivity.setId(reqClubActivity.getActivityId());
        }
        //非日常活动没有活动报名截止时间，直接使用活动开始时间做截止时间
        if (!reqClubActivity.getActivityType().equals(Constants.BYTE_ZERO)) {
            reqClubActivity.setSignEndTime(reqClubActivity.getEndTime());
        }
        if (reqClubActivity.getStartTime().getTime() <=
                System.currentTimeMillis() ||
                reqClubActivity.getStatus().equals(Constants.BYTE_TWO)) {
            return APIResponse.returnFail("活动已经开始，无法修改");
        }
        validSaveActivityRequest(reqClubActivity);
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdEqualTo(reqClubActivity.getId());
        List<TbClubActivity> tbClubActivityList = tbClubActivityMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tbClubActivityList)) {
            return APIResponse.returnFail("该活动不存在");
        }
        TbClubActivity tbClubActivity = tbClubActivityList.get(0);
        if(!tbClubActivity.getActivityCycle() && reqClubActivity.getActivityCycle())
        {
            //普通活动转化为日循环活动,设置当前活动为根循环活动
            tbClubActivity.setActivityRoot(tbClubActivity.getActivityId());
        }else if(tbClubActivity.getActivityCycle() && reqClubActivity.getActivityCycle())
        {
            //周期活动继续编辑
            if(StringUtil.isBlankOrNull(tbClubActivity.getCycleRange())
                    && !StringUtil.isBlankOrNull(reqClubActivity.getCycleRange()))
            {
                //非日循环转日循环,设置当前活动为根循环活动
                tbClubActivity.setActivityRoot(tbClubActivity.getActivityId());
            }
            else if(!StringUtil.isBlankOrNull(tbClubActivity.getCycleRange())
                    && !StringUtil.isBlankOrNull(reqClubActivity.getCycleRange()))
            {
                if(!reqClubActivity.getCycleRange().equals(tbClubActivity.getCycleRange()) &&
                        !tbClubActivity.getActivityRoot().equals(reqClubActivity.getActivityId()))
                {
                    return APIResponse.returnFail("子周期活动不可重设周期。");
                }
            }

        }
        //APP2.0已报名不可修改价格
        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria().andActivityIdEqualTo(reqClubActivity.getActivityId())
                .andStatusEqualTo(1);
        int userCount = signUserMapper.countByExample(signUserExample);
        if (userCount > 0) {
            if (reqClubActivity.getLimitNum() != 0 && userCount > reqClubActivity.getLimitNum()) {
                return APIResponse.returnFail("修改的限制人数小于已经报名人数。");
            }
            try {
                if (reqClubActivity.getFeeType().equals(Constants.BYTE_ZERO)) {
                    boolean b1 = ActivityUtils.dequals(tbClubActivity.getAaTotal(), reqClubActivity.getAaTotal());
                    boolean b2 = ActivityUtils.dequals(tbClubActivity.getAaFee(), reqClubActivity.getAaFee());
                    if (!(b1 && b2)) {
                        return APIResponse.returnFail("已经有人报名该活动，不能再编辑价格咯~");
                    }
                } else if (reqClubActivity.getFeeType().equals(Constants.BYTE_ONE)) {
                    boolean b1 = ActivityUtils.dequals(tbClubActivity.getFemaleFee(), reqClubActivity.getFemaleFee());
                    boolean b2 = ActivityUtils.dequals(tbClubActivity.getFemaleMemberFee(), reqClubActivity.getFemaleMemberFee());
                    boolean b3 = ActivityUtils.dequals(tbClubActivity.getMaleFee(), reqClubActivity.getMaleFee());
                    boolean b4 = ActivityUtils.dequals(tbClubActivity.getMaleMemberFee(), reqClubActivity.getMaleMemberFee());
                    if (!(b1 && b2 && b3 && b4)) {
                        return APIResponse.returnFail("已经有人报名该活动，不能再编辑价格咯~");
                    }
                }
            } catch (NullPointerException npe) {
                return APIResponse.returnFail("必填费用参数有空值");
            }
        }
        //地址校准
        PlaceDubboProvider place = null;
        if(null != reqClubActivity.getPlaceId() && reqClubActivity.getPlaceId() > 0)
        {
            place = activitySupportService.getActivityPlace(reqClubActivity.getPlaceId());
            if(null == place)
            {
                throw new BizException("获取不到场馆的城市区域呀，等会再编辑呗！");
            }
            reqClubActivity.setCityId(place.getCityId());
            reqClubActivity.setDistrictId(place.getDistrictId());
        }else if(reqClubActivity.getCityId() == 0){
            Double lat = reqClubActivity.getLat();
            Double lng = reqClubActivity.getLng();
            BaiduLBS lbs = new BaiduLBS();
            AddressComponent addressComponent =
                    lbs.getAddressComponentByLatAndLng(lat, lng);
            logger.warn("addressComponent" + JSONObject.toJSONString(addressComponent));
            tbClubActivity.setLat(lat);
            tbClubActivity.setLng(lng);
            TbCityExample cityExample = new TbCityExample();
            String cityName = addressComponent.getCity();
            cityName = cityName.substring(0, cityName.length()-1);
            cityExample.createCriteria().andNameLike(cityName + "%");
            List<TbCity> cities = tbCityMapper.selectByExample(cityExample);
            if(com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(cities))
            {
                logger.warn("活动地点信息：" + JSONObject.toJSONString(reqClubActivity));
                throw new BizException("你所选的地址无法使用，请联系工作人员");
            }
            if (null != cities && cities.size() == 1) {
                TbCity city = cities.get(0);
                tbClubActivity.setCityId(city.getId());
                reqClubActivity.setCityId(city.getId());
                TbDistrictExample districtExample = new TbDistrictExample();
                districtExample.createCriteria()
                        .andNameEqualTo(addressComponent.getDistrict())
                        .andCityIdEqualTo(city.getId());
                List<TbDistrict> districts =
                        tbDistrictMapper.selectByExample(districtExample);
                logger.warn("通过经纬度查询到城市：" + JSONObject.toJSONString(city) +
                        "区域：" + JSONObject.toJSONString(districts));
                if (null != districts && districts.size() == 1) {
                    TbDistrict district = districts.get(0);
                    tbClubActivity.setDistrictId(district.getId());
                    reqClubActivity.setDistrictId(district.getId());
                }
            }
        }

        TbActivity tbActivity = new TbActivity();
        TbActivityPoster tbActivityPoster = new TbActivityPoster();
        TbActivityDesc tbActivityDesc = new TbActivityDesc();
        //编辑活动通用信息 调用活动接口
        List<TbActivityMultimedia> tbActivityMultimedias = new ArrayList<TbActivityMultimedia>();
        convertActivityReqToDb(reqClubActivity,tbClubActivity, tbActivity,
                tbActivityPoster, tbActivityDesc,tbActivityMultimedias, 2);
        int activityCount = tbActivityMapper.updateByPrimaryKeySelective(tbActivity);
        if(activityCount <= 0)
        {
            throw new BizException("亲，遭遇核弹冲击，更新活动失败了哟~");
        }
        int descCount = tbActivityDescMapper.updateByPrimaryKeySelective(tbActivityDesc);
        if(activityCount <= 0)
        {
            throw new BizException("亲，遭遇核弹冲击，更新活动描述失败了哟~");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("activityId", reqClubActivity.getActivityId());
        if(tbActivityMultimedias.size() > 0)
        {
            int mediaUpdateCount = clubActivityCRUDMapper.batchUpdateDelete(map);
            int mediaInsertcount = clubActivityCRUDMapper.batchInsertMedia(tbActivityMultimedias);
            if(mediaInsertcount <= 0)
            {
                throw new BizException("亲，遭遇核弹冲击，更新活动相册失败了哟~");
            }
        }
        int clubActivitycount = tbClubActivityMapper.updateByPrimaryKeySelective(tbClubActivity);
        if(clubActivitycount <= 0)
        {
            throw new BizException("亲，遭遇核弹冲击，更新俱乐部活动失败了哟~");
        }
        RespClubActivity respClubActivity = selectClubActivityById(reqClubActivity.getActivityId());
        activitySupportService.afterUpdateActivity(respClubActivity);
        return APIResponse.returnSuccess(respClubActivity);
    }

    @Override
    public APIResponse<RespClubActivity> queryClubActivityById(Integer activityId, Integer uid) {
        boolean isAdmin = false;
        logger.warn("开始获取活动基本信息");
        RespClubActivity respClubActivity = getActivityDetail(activityId, uid);
        if(null == respClubActivity) {
            return APIResponse.returnFail("活动不存在");
        }
        int clubId = respClubActivity.getClubId();
        if (null != uid) {
            //当前用户在俱乐部的权限信息
            TbClubMember clubMember = clubMemberService.queryClubMember(uid, clubId);
            if(null != clubMember)
            {
                respClubActivity.setIsClubMember(1);//俱乐部成员
                respClubActivity.setRoleCode(clubMember.getRoleCode());
                if(clubMember.getPriority() < 4)
                {
                    isAdmin = true;
                }
            }
        }
        logger.warn("开始获取报名成员");
        List<RespClubActivityMember> signUsers =
                activityAccountService.buildClubActivityMember(uid, activityId,clubId, false, isAdmin);
        respClubActivity.setSignUserList(signUsers);
        //APP3.0需求 活动详情展示最近一条活动评价
        logger.warn("开始获取活动评价");
        ReqClubCommentPage reqClubCommentPage = new ReqClubCommentPage();
        reqClubCommentPage.setPageNum(0);
        reqClubCommentPage.setPageSize(1);
        reqClubCommentPage.setClubId(respClubActivity.getClubId());
        reqClubCommentPage.setActivityId(activityId);
        PageObj<List<RespClubComment>> commentList =
                clubCommentService.getClubCommentList(reqClubCommentPage);
        if(null != commentList)
        {
            List<RespClubComment> comments = commentList.getItems();
            if(null != comments && comments.size() == 1)
            {
                respClubActivity.setLastComment(comments.get(0));
            }
        }

        return APIResponse.returnSuccess(respClubActivity);
    }

    public RespClubActivity getActivityDetail(Integer activityId, Integer uid)
    {
        RespClubActivity respClubActivity = new RespClubActivity();
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria().andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubActivity> clubActivities = tbClubActivityMapper.selectByExample(clubActivityExample);
        if (null == clubActivities || clubActivities.size() == 0) {
            return null;
        }
        TbClubActivity clubActivity = clubActivities.get(0);
        TbActivity tbActivity = tbActivityMapper.selectByPrimaryKey(activityId);
        if (null == tbActivity)
        {
            return null;
        }
        TbActivityDescExample activityDescExample = new TbActivityDescExample();
        activityDescExample.createCriteria().andActivityIdEqualTo(activityId);
        List <TbActivityDesc> activityDescs = tbActivityDescMapper.selectByExample(activityDescExample);
        TbActivityDesc tbActivityDesc = activityDescs.get(0);
        TbActivityMultimediaExample activityMultimediaExample = new TbActivityMultimediaExample();
        activityMultimediaExample.createCriteria().andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo(false);
        List<TbActivityMultimedia> activityMultimedias =
                tbActivityMultimediaMapper.selectByExample(activityMultimediaExample);
        //活动海报
        Integer posterPicId = tbActivity.getPosterPicId();
        TbActivityPoster tbActivityPoster;
        if (null != posterPicId && posterPicId != 0) {
            tbActivityPoster = tbActivityPosterMapper.selectByPrimaryKey(posterPicId);

        } else {
            tbActivityPoster = new TbActivityPoster();
            logger.warn("活动海报未查到，活动ID：" + activityId + "海报ID：" + posterPicId);
        }

        //如果没有群聊ID
        if(StringUtils.isBlank(tbActivity.getGroupId()))
        {
            TbActivity updateActivity = new TbActivity();
            updateActivity.setId(activityId);
            String groupId = activitySupportService.createGroup(tbActivity.getName(),
                    clubActivity.getUid(), tbActivityPoster.getUrl());
            if(StringUtils.isNotEmpty(groupId)) {
                updateActivity.setGroupId(groupId);
                int updateCount = tbActivityMapper.updateByPrimaryKeySelective(updateActivity);
                if(updateCount <= 0)
                {
                    logger.warn("查看详情时更新群聊ID失败。活动ID：" + activityId);
                }
            }

        }
        //包装活动详情对象
        convertActivityDbToResp(respClubActivity, clubActivity, tbActivity, tbActivityPoster,
                tbActivityDesc, activityMultimedias);
        Map<Integer, String> categoryMaps = activitySupportService.getCategoryMap();
        if(categoryMaps.containsKey(respClubActivity.getCategoryId()))
        {
            respClubActivity.setCategoryName(categoryMaps.get(respClubActivity.getCategoryId()));
        }
        if(StringUtils.isEmpty(respClubActivity.getCategoryName()))
        {
            respClubActivity.setCategoryName("其他");
        }
        respClubActivity.setIsCollect(isCollect(activityId, uid));
        if(respClubActivity.getClubId() == null || respClubActivity.getClubId() == 0) {
            return null;
        }
        return respClubActivity;
    }

    @Override
    public APIResponse<RespClubActivity> queryClubActivityByAdmin(Integer activityId, Integer uid) {
        logger.warn("开始获取活动基本信息");
        RespClubActivity respClubActivity = getActivityDetail(activityId, uid);
        if(null == respClubActivity)
        {
            return APIResponse.returnFail("该活动不存在");
        }
        int clubId = respClubActivity.getClubId();
        TbClubMember clubMember = clubMemberService.queryClubMember(uid, clubId);
        if(null == clubMember)
        {
            return APIResponse.returnFail("没有查看权限");
        }
        respClubActivity.setIsClubMember(1);//俱乐部成员
        respClubActivity.setRoleCode(clubMember.getRoleCode());
        logger.warn("开始获取报名成员");
        List<RespClubActivityMember> signUsers =
                activityAccountService.buildClubActivityMember(uid, activityId,clubId, true, true);
        respClubActivity.setSignUserList(signUsers);
        respClubActivity.setSignUpMoney(activityAccountService.activityAccountOnline(activityId));
        return APIResponse.returnSuccess(respClubActivity);
    }

    @Override
    public RespClubActivity selectClubActivityById(Integer activityId) {
        RespClubActivity respClubActivity = new RespClubActivity();
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria().andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubActivity> clubActivities = tbClubActivityMapper.selectByExample(clubActivityExample);
        if (null == clubActivities || clubActivities.size() == 0) {
            return null;
        }
        TbClubActivity clubActivity = clubActivities.get(0);
        TbActivity tbActivity = tbActivityMapper.selectByPrimaryKey(activityId);
        if (null == tbActivity)
        {
            return null;
        }
        TbActivityDescExample activityDescExample = new TbActivityDescExample();
        activityDescExample.createCriteria().andActivityIdEqualTo(activityId);
        List <TbActivityDesc> activityDescs = tbActivityDescMapper.selectByExample(activityDescExample);
        TbActivityDesc tbActivityDesc = activityDescs.get(0);
        //活动海报
        Integer posterPicId = tbActivity.getPosterPicId();
        TbActivityPoster tbActivityPoster;
        if (null != posterPicId && posterPicId != 0) {
            tbActivityPoster = tbActivityPosterMapper.selectByPrimaryKey(posterPicId);

        } else {
            tbActivityPoster = new TbActivityPoster();
        }
        //包装活动详情对象
        convertActivityDbToResp(respClubActivity, clubActivity, tbActivity, tbActivityPoster,
                tbActivityDesc, null);
        Map<Integer, String> categoryMaps = activitySupportService.getCategoryMap();
        if(categoryMaps.containsKey(respClubActivity.getCategoryId()))
        {
            respClubActivity.setCategoryName(categoryMaps.get(respClubActivity.getCategoryId()));
        }
        if(StringUtils.isEmpty(respClubActivity.getCategoryName()))
        {
            respClubActivity.setCategoryName("其他");
        }
        //respClubActivity.setIsCollect(isCollect(activityId, uid));
        return respClubActivity;
    }

    @Override
    public APIResponse<RespShareActivity> shareClubActivityById(Integer activityId, HttpServletRequest request) {
        return null;
    }

    @Override
    public APIResponse<PageObj<List<RespClubActivity>>> queryActivityListCollect(Integer uid, Integer pageIndex, Integer pageSize) {
        return null;
    }

    @Override
    public PageObj<List<RespClubActivity>> clubActivityList(ReqClubActivitySearch reqClubActivitySearch, Integer userId) {

        return null;
    }

    @Override
    public PageObj<List<RespClubActivity>> clubActivityListByCriteria(
            ReqClubActivityCondition reqClubActivityCondition, Integer userId)
    {
        Integer clubId = reqClubActivityCondition.getClubId();
        if(null == clubId || clubId == 0) {
            reqClubActivityCondition.setClubIds(
                    clubActivityCRUDMapper.queryClubIdsByUid(userId));
        }
        Integer pageNum = reqClubActivityCondition.getPageNum() + 1;
        Integer pageSize = reqClubActivityCondition.getPageSize();
        List<RespClubActivity> resp = new ArrayList<RespClubActivity>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isAdmin", 0);
        Integer status = reqClubActivityCondition.getStatus();
        if(null != clubId && clubId > 0) {
            map.put("clubId", clubId);
            if(null != userId && clubMemberService.isClubAdminMember(userId, clubId)) {
                map.put("isAdmin", 1);
            }
        } else if(CollectionUtils.isEmpty(reqClubActivityCondition.getClubIds())) {
            return PageObj.create(0, pageNum, pageSize, resp);
        } else {
            map.put("clubIds", reqClubActivityCondition.getClubIds());
        }
        if(null != status && status > 0)
        {
            map.put("status", reqClubActivityCondition.getStatus());
        }
        String activityName = reqClubActivityCondition.getActivityName();
        if(null != activityName && !"".equals(activityName))
        {
            map.put("activityName", activityName);
        }
        int total = clubActivityCRUDMapper.countClubActivityListByCriteria(map);
        if(total <= 0)
        {
            return PageObj.create(0, pageNum, pageSize, resp);
        }
        Limit limit = Limit.buildLimit(pageNum, pageSize);
        map.put("pageStart", limit.getStart());
        map.put("pageSize", limit.getSize());
        logger.warn("查询俱乐部活动列表：" + JSONObject.toJSONString(map));
        resp = clubActivityCRUDMapper.queryClubActivityListByCriteria(map);
        activitySupportService.getActivityPlaces(resp, reqClubActivityCondition.getLng(),
                reqClubActivityCondition.getLat());
        PageObj<List<RespClubActivity>> pageObj = PageObj.create(total,pageNum,pageSize,resp);
        return pageObj;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse suspendActivity(ReqSuspendInfo reqSuspendInfo) {
        TbClubActivityExample tbClubActivityExample=new TbClubActivityExample();
        tbClubActivityExample.createCriteria().andActivityIdEqualTo(reqSuspendInfo.getActivityId()).andIsDeleteEqualTo((byte)0);
        List<TbClubActivity> tbClubActivityList=tbClubActivityMapper.selectByExample(tbClubActivityExample);

        if (CollectionUtils.isEmpty(tbClubActivityList)){
            return APIResponse.returnFail(ApiResponseEnum.RESOURCE_NOT_FOUND.getId(), "活动不存在");
        }
        TbClubActivity tbClubActivity=tbClubActivityList.get(0);
        if (!clubMemberService.isClubAdminMember(reqSuspendInfo.getUid(), tbClubActivity.getClubId())) {//校验只有管理员主席可以暂停
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED.getId(),"请先加入俱乐部并努力获取管理员权限。");
        }
        TbActivity activity = tbActivityMapper.selectByPrimaryKey(reqSuspendInfo.getActivityId());
        if (!activity.getStatus().equals(Constants.BYTE_ZERO)){//已暂停不可重复暂停
            return APIResponse.returnFail("该活动已取消或已暂停，不能暂停。");
        }
        if (!DateUtils.dateCompare(activity.getEndTime(), new Date(), false)){//当前时间小于活动结束时间 可暂停
            return APIResponse.returnFail(ApiResponseEnum.RESOURCE_NOT_FOUND.getId(), "活动已结束，没有暂停的必要啦！");
        }
        TbActivity updateActivity = new TbActivity();
        updateActivity.setStatus(Constants.BYTE_ONE);
        updateActivity.setId(activity.getId());
        int activityCount = tbActivityMapper.updateByPrimaryKeySelective(updateActivity);
        if(activityCount <= 0)
        {
            throw new BizException("暂停活动失败：" + JSONObject.toJSONString(updateActivity));
        }
        TbClubActivity updateClubActivity = new TbClubActivity();
        updateClubActivity.setId(tbClubActivity.getId());
        updateClubActivity.setActivityStatus(Constants.FLOAT_PAUSE);//设置为已暂停
        int count =tbClubActivityMapper.updateByPrimaryKeySelective(updateClubActivity);//更改活动状态为暂停
        if (count <= 0){//删除solr搜索条件
            throw new BizException("暂停活动失败：" + JSONObject.toJSONString(updateClubActivity));
        }
        activitySupportService.afterSuspendActivity(tbClubActivity.getActivityId(), tbClubActivity.getClubId());
        return APIResponse.returnSuccess("暂停报名成功");
    }

    /**
     * 恢复暂停活动
     *
     * @param reqSuspendInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse reSuspendActivity(ReqSuspendInfo reqSuspendInfo) {
        Integer activityId = reqSuspendInfo.getActivityId();
        TbClubActivityExample tbClubActivityExample = new TbClubActivityExample();
        tbClubActivityExample.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo((byte) 0);
        List<TbClubActivity> tbClubActivityList = tbClubActivityMapper.selectByExample(tbClubActivityExample);

        if (CollectionUtils.isEmpty(tbClubActivityList)) {
            return APIResponse.returnFail("活动不存在");
        }
        TbClubActivity tbClubActivity = tbClubActivityList.get(0);
        if (!clubMemberService.isClubAdminMember(reqSuspendInfo.getUid(), tbClubActivity.getClubId())) {//校验只有管理员主席可以暂停
            return APIResponse.returnFail("请先加入俱乐部并努力获取管理员权限。");
        }
        TbActivity activity = tbActivityMapper.selectByPrimaryKey(reqSuspendInfo.getActivityId());
        if (activity.getStatus().equals(Constants.BYTE_ZERO)) {
            return APIResponse.returnFail("该活动已是正常报名状态，不需要恢复。");
        }
        if (!DateUtils.dateCompare(activity.getEndTime(), new Date(), false)){//当前时间小于活动结束时间 可暂停
            return APIResponse.returnFail(ApiResponseEnum.RESOURCE_NOT_FOUND.getId(), "活动已结束，没有恢复的必要啦！");
        }
        float activityStatus = 0.0f;
        if (activity.getEndTime().getTime() <= System.currentTimeMillis()) {
            activityStatus = 2f;
        } else {
            if (activity.getSignEndTime().getTime() <= activity.getStartTime().getTime()) {
                if (activity.getStartTime().getTime() <= System.currentTimeMillis()) {
                    activityStatus = 1f;
                }
            } else {
                if (activity.getSignEndTime().getTime() <= System.currentTimeMillis()) {
                    activityStatus = 1f;
                }
            }
        }
        TbClubActivity updateClubActivity = new TbClubActivity();
        updateClubActivity.setId(tbClubActivity.getId());
        updateClubActivity.setActivityStatus(activityStatus);
        logger.warn("更新活动状态为：" + activityStatus);
        int count = tbClubActivityMapper.updateByPrimaryKeySelective(updateClubActivity);
        if (count <= 0) {
            throw new BizException("恢复暂停活动失败：" + JSONObject.toJSONString(updateClubActivity));
        }
        TbActivity updateActivity = new TbActivity();
        updateActivity.setStatus(Constants.BYTE_ZERO);
        updateActivity.setId(activityId);
        int activityCount = tbActivityMapper.updateByPrimaryKeySelective(updateActivity);
        if (activityCount <= 0) {
            throw new BizException("恢复暂停活动失败：" + JSONObject.toJSONString(updateActivity));
        }
        RespClubActivity respClubActivity = selectClubActivityById(activityId);
        activitySupportService.afterReSuspendActivity(respClubActivity);
        return APIResponse.returnSuccess("恢复正常报名成功");
    }

    /**
     * 取消活动 点击取消活动，判断是否超过活动结束时间 如果超过跳出提示不可取消， <p> 如果没超过跳出提示，是否取消活动，点是则取消活动， 退回所有报名人的款项 退款 记录流水
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse cancelActivity(Integer activityId, Integer uid, boolean isAdmin) {
        RespClubActivity respClubActivity = selectClubActivityById(activityId);
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubActivity> clubActivityList = tbClubActivityMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(clubActivityList)) {
            return APIResponse.returnFail("活动不存在!");
        }
        TbClubActivity tbClubActivity = clubActivityList.get(0);
        if (!clubMemberService.isClubAdminMember(uid, tbClubActivity.getClubId())) {
            return APIResponse.returnFail("请先加入俱乐部并努力获取管理员权限。");
        }
        if (!isAdmin && !DateUtils.dateCompare(respClubActivity.getEndTime(), new Date(), false)) {//当前时间小于活动结束时间 可取消
            return APIResponse.returnFail("活动已结束，不可取消！");
        }
        //先取消活动表的活动
        TbActivity cancelActivity = new TbActivity();
        cancelActivity.setId(activityId);
        cancelActivity.setStatus(Constants.BYTE_TWO);
        int result = tbActivityMapper.updateByPrimaryKeySelective(cancelActivity);
        if (result <= 0) {
            throw new BizException("取消活动失败");
        }
        //再取消俱乐部活动表的活动

        TbClubActivity updateClubActivity = new TbClubActivity();
        updateClubActivity.setId(tbClubActivity.getId());
        updateClubActivity.setActivityStatus(3f);
        int clubActivityCount = tbClubActivityMapper.updateByPrimaryKeySelective(updateClubActivity);
        if (clubActivityCount <= 0) {
            throw new BizException("取消活动失败");
        }
        //processRefundOrderActivity(respClubActivity, activityId, "活动发起人取消活动", null, (byte) 3);
        return APIResponse.returnFail("取消活动失败!");
    }

    @Override
    public PageObj<List<RespActivityPoster>> selectActivityPosterList(Integer pageNum, Integer pageSize, Integer categoryId, Integer clubId) {
        return null;
    }

    @Override
    public APIResponse batchAddActivityPoster(List<String> urls, int uid, int categoryId, int clubId) {
        return null;
    }

    @Override
    public APIResponse batchDeleteActivityPoster(List<Integer> posterIds, int clubId, int uid) {
        return null;
    }

    @Override
    public APIResponse getAppraiseSetting()
    {
        ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
        reqCommentQuery.setSystemCode(Constants.CLUB_SYSTEM_CODE);
        reqCommentQuery.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
        RespCommentTagAndCommentDetail respCommentTagAndCommentDetail =
                commentServiceFacade.getCommentTagAndCommentDetail(reqCommentQuery);
        return APIResponse.returnSuccess(respCommentTagAndCommentDetail);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse activityAppraise(Integer userId, ReqActivityComment reqActivityComment) {
        int activityId = reqActivityComment.getActivityId();
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria().andActivityIdEqualTo(activityId)
                .andActivityStatusNotEqualTo(3f)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubActivity> list =
                tbClubActivityMapper.selectByExample(clubActivityExample);
        if(null == list || list.size() != 1)
        {
            return APIResponse.returnFail("活动不存在");
        }
        TbClubActivity tbClubActivity = list.get(0);
        TbActivity tbActivity = tbActivityMapper.selectByPrimaryKey(activityId);
        int uid = tbClubActivity.getUid();
        int clubId = tbClubActivity.getClubId();
        if(reqActivityComment.getCommentType() == 2)
        {
            if(!clubMemberService.isClubAdminMember(uid, clubId))
            {
                return APIResponse.returnFail("非管理员无法回复评价！");
            }
            ReqIsComment reqIsComment = new ReqIsComment();
            reqIsComment.setUid(userId);
            if(null == reqActivityComment.getReplayId() ||
                    reqActivityComment.getReplayId() == 0)
            {
                return APIResponse.returnFail("回复评价ID必填！");
            }
            reqIsComment.setReplaceId(reqActivityComment.getReplayId());
            if(commentServiceFacade.checkIsReplace(reqIsComment))
            {
                return APIResponse.returnFail("只能回复一次噢！");
            }
        }
        if(reqActivityComment.getCommentType() == 1)
        {
            APIResponse validResp = activitySupportService.validAppraise(
                    tbActivity, tbClubActivity, userId, reqActivityComment.getBusinessOrderNo());
            if(!validResp.isRet())
            {
                return validResp;
            }
        }
        com.quanyan.comment.reqeust.ReqCommentParam reqCommentParam =
                new com.quanyan.comment.reqeust.ReqCommentParam();
        reqCommentParam.setSystemCode(Constants.CLUB_SYSTEM_CODE);
        reqCommentParam.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
        reqCommentParam.setBusinessId(activityId);
        reqCommentParam.setCommentContent(reqActivityComment.getContent());
        //是否匿名
        reqCommentParam.setAnonymous(reqActivityComment.getAnonymous().byteValue());
        //评论
        reqCommentParam.setCommentType(reqActivityComment.getCommentType());
        reqCommentParam.setCommonParam(clubId);
        reqCommentParam.setFromUserId(userId);
        //回复
        reqCommentParam.setToUserId(reqActivityComment.getToUserId());
        reqCommentParam.setReplayId(reqActivityComment.getReplayId());
        //打分项
        List<Map<String, Object>> lstCommentDetailScore = new ArrayList<Map<String, Object>>();
        ReqCommentDetailScore score = new ReqCommentDetailScore();
        List<ReqCommentDetailScore> maps = reqActivityComment.getReqCommentDetailScores();
        Double addScore = 0.0;
        if(null != maps && maps.size() > 0)
        {
            for(ReqCommentDetailScore map : maps)
            {
                addScore += map.getScore();
                lstCommentDetailScore.add(map.toMap());
            }
            reqCommentParam.setLstCommentDetailScore(lstCommentDetailScore);
        }
        if (null != reqActivityComment.getLstPic() && reqActivityComment.getLstPic().size() > 0 ) {
            reqCommentParam.setLstPic(reqActivityComment.getLstPic());
        }
        reqCommentParam.setScore(addScore/2.0);
        logger.warn("开始调用评论系统，入参：{}" + reqCommentParam);
        APIResponse apiResponse = commentServiceFacade.commentAdd(reqCommentParam);
        if (!apiResponse.isRet()) {
            logger.error("调用评论系统失败, 失败信息: " + apiResponse.getErrmsg());
            throw new BizException("调用评论系统失败, 失败信息: " + apiResponse.getErrmsg());
        }
        if(reqActivityComment.getCommentType() == 2)
        {
            return APIResponse.returnSuccess();
        }
        activitySupportService.afterAppraise(tbClubActivity, tbActivity, userId, addScore);
        return APIResponse.returnSuccess();
    }

    private void validSaveActivityRequest(ReqClubActivity reqClubActivity)
    {
        if(null == reqClubActivity.getLat() || reqClubActivity.getLat().doubleValue() == 0
                || null == reqClubActivity.getLng() || reqClubActivity.getLng().doubleValue() == 0)
        {
            throw new BizException("你的活动举行地点经纬度不存在，请重新创建/编辑。");
        }
        if(!CommonUtils.validName(reqClubActivity.getName()))
        {
            throw new BizException("活动名称只允许输入中文，英文，数字");
        }
        if(CollectionUtils.isNotEmpty(reqClubActivity.getActivityMediaList()))
        {
            if(reqClubActivity.getActivityMediaList().size() > 20)
            {
                throw new BizException("活动相册不允许超过20张");
            }
        }
        //非日常活动没有活动报名截止时间，直接使用活动结束时间做截止时间
        if (!reqClubActivity.getActivityType().equals(Constants.BYTE_ZERO)) {
            reqClubActivity.setSignEndTime(reqClubActivity.getEndTime());
        }
        if (reqClubActivity.getSignEndTime().getTime() >
                reqClubActivity.getEndTime().getTime()) {
            throw new BizException("报名截止时间比活动结束时间晚");
        }
        //APP 11需求，取消最小报名人数
        if (null == reqClubActivity.getSignUpMin()) {
            reqClubActivity.setSignUpMin(0);
        }
        if (reqClubActivity.getStartTime().getTime() < System.currentTimeMillis()) {
            throw new BizException("活动开始时间小于当前时间");
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("clubId", reqClubActivity.getClubId());
        queryMap.put("fromStartTime", DateUtils.getTargetTimesmorning(reqClubActivity.getStartTime()));
        queryMap.put("toStartTime", DateUtils.getTargetTimesnight(reqClubActivity.getStartTime()));
        queryMap.put("statusList", Arrays.asList(0,1));
        if(reqClubActivity.getActivityId() != null)
        {
            queryMap.put("expectActivityId", reqClubActivity.getActivityId());
        }
        int todayCount = clubActivityCRUDMapper.countClubActivityListByFree(queryMap);
        if(todayCount >= 6)
        {
            List<Integer> expectClubId = Arrays.asList(360,639,9,156,2,6411,129,3573,4495,109,347,34,4455,133);
            if(expectClubId.contains(reqClubActivity.getClubId().intValue())) {
                if(todayCount >= 10) {
                    throw new BizException("当天已经有10个活动了，休息休息吧！");
                }
            } else {
                throw new BizException("当天已经有6个活动了，休息休息吧！");
            }
        }
        //APP2.0限制报名人数上下线校验
        if (reqClubActivity.getLimitNum() > 0) {
            if (null != reqClubActivity.getSignUpMin() &&
                    reqClubActivity.getSignUpMin() > reqClubActivity.getLimitNum()) {
                throw new BizException("最少报名人数大于限制总人数");
            }
        }
        //设置weekRange
        reqClubActivity.setWeekRange(DateUtils.getDayOfWeek(reqClubActivity.getStartTime()).byteValue());
        if(null != reqClubActivity.getCycleRange()
                && !"".equals(reqClubActivity.getCycleRange()))
        {
            if(!reqClubActivity.getCycleRange().contains(reqClubActivity.getWeekRange().toString()))
            {
                throw new BizException("周期活动创建/编辑必须勾选开始时间当天！");
            }
            reqClubActivity.setCycleRange(ActivityUtils.sortString(reqClubActivity.getCycleRange()));
        }
        reqClubActivity.setIsPrimeTime(Constants.BYTE_ZERO);
        //判断 是否包含黄金时段 19-22为黄金时段
        if(ActivityUtils.isContainPrimeTime(
                reqClubActivity.getStartTime(), reqClubActivity.getEndTime()))
        {
            reqClubActivity.setIsPrimeTime(Constants.BYTE_ONE);
        }
    }

    /**
     *
     * @param reqClubActivity
     * @param tbClubActivity
     * @param tbActivity
     * @param tbActivityPoster
     * @param tbActivityDesc
     * @param tbActivityMultimedias
     * @param operate 1Create 2Update
     */
    private void convertActivityReqToDb(ReqClubActivity reqClubActivity,
                                        TbClubActivity tbClubActivity,
                                        TbActivity tbActivity,
                                        TbActivityPoster tbActivityPoster,
                                        TbActivityDesc tbActivityDesc,
                                        List<TbActivityMultimedia> tbActivityMultimedias,
                                        int operate)
    {
        if(null == reqClubActivity)
        {
            return;
        }
        Integer posterId = reqClubActivity.getPosterPicId();
        TbActivityPoster poster = tbActivityPosterMapper.selectByPrimaryKey(posterId);
        if(null != tbActivity)
        {
            tbActivity.setLimitNum(reqClubActivity.getLimitNum());
            tbActivity.setName(reqClubActivity.getName());
            tbActivity.setPlaceId(reqClubActivity.getPlaceId());
            tbActivity.setPlaceAddress(reqClubActivity.getPlaceAddress());
            tbActivity.setPosterPicId(posterId);
            tbActivity.setSignEndTime(reqClubActivity.getSignEndTime());
            tbActivity.setStartTime(reqClubActivity.getStartTime());
            tbActivity.setEndTime(reqClubActivity.getEndTime());
            tbActivity.setRequireField(reqClubActivity.getRequireField());
            //创建时可设置
            if(operate == 1)
            {
                tbActivity.setSignStartTime(new Date());
                tbActivity.setCategoryId(reqClubActivity.getCategoryId());
                tbActivity.setGroupId(activitySupportService.createGroup(reqClubActivity.getName(),
                        reqClubActivity.getUid(), poster.getUrl()));
                tbActivityMapper.insertSelective(tbActivity);
            }else if(operate == 2)
            {
                tbActivity.setId(reqClubActivity.getActivityId());
            }
            logger.warn("reqClubActivity:" + JSONObject.toJSONString(reqClubActivity)
                    + "tbActivity:" + JSONObject.toJSONString(tbActivity));
        }
        if(null != tbClubActivity)
        {
            if(operate == 1)
            {
                tbClubActivity.setActivityId(tbActivity.getId());
                tbClubActivity.setUid(reqClubActivity.getUid());
                tbClubActivity.setActivityType(reqClubActivity.getActivityType());
                tbClubActivity.setClubId(reqClubActivity.getClubId());
                tbClubActivity.setCategoryId(reqClubActivity.getCategoryId());
                tbClubActivity.setCityId(reqClubActivity.getCityId());
                tbClubActivity.setActivityRoot(tbActivity.getId());
                tbClubActivity.setDistrictId(reqClubActivity.getDistrictId());
            }
            tbClubActivity.setMobile(reqClubActivity.getMobile());
            tbClubActivity.setPlanner(reqClubActivity.getPlanner());
            tbClubActivity.setFeeType(reqClubActivity.getFeeType());
            tbClubActivity.setAaFee(reqClubActivity.getAaFee());
            tbClubActivity.setAaTotal(reqClubActivity.getAaTotal());
            tbClubActivity.setFemaleFee(reqClubActivity.getFemaleFee());
            tbClubActivity.setFemaleMemberFee(reqClubActivity.getFemaleMemberFee());
            tbClubActivity.setMaleFee(reqClubActivity.getMaleFee());
            tbClubActivity.setMaleMemberFee(reqClubActivity.getMaleMemberFee());

            tbClubActivity.setIsPrimeTime(reqClubActivity.getIsPrimeTime());
            tbClubActivity.setActivityCycle(reqClubActivity.getActivityCycle());
            tbClubActivity.setCancelTimeLimit(reqClubActivity.getCancelTimeLimit());
            tbClubActivity.setFaceLevel(reqClubActivity.getFaceLevel());
            tbClubActivity.setIsCancelSignUp(reqClubActivity.getIsCancelSignUp());
            tbClubActivity.setWeekRange(reqClubActivity.getWeekRange());
            tbClubActivity.setSignUpType(reqClubActivity.getSignUpType());
            tbClubActivity.setCycleRange(reqClubActivity.getCycleRange());
            if(operate == 2)
            {
                if(null != reqClubActivity.getCityId() && reqClubActivity.getCityId() > 0)
                {
                    tbClubActivity.setCityId(reqClubActivity.getCityId());
                }
                if(null != reqClubActivity.getDistrictId() && reqClubActivity.getDistrictId() > 0)
                {
                    tbClubActivity.setDistrictId(reqClubActivity.getDistrictId());
                }
            }
            tbClubActivity.setLat(reqClubActivity.getLat());
            tbClubActivity.setLng(reqClubActivity.getLng());
            logger.warn("tbClubActivity:" + JSONObject.toJSONString(tbClubActivity));
        }
        if(null != tbActivityDesc)
        {
            ActivityDesc desc = reqClubActivity.getActivityDesc();
            if(null != desc)
            {
                tbActivityDesc.setBodyDesc(desc.getBodyDesc());
                tbActivityDesc.setActivityId(tbActivity.getId());
                //更新时关联原始ID
                if(operate == 2)
                {
                    TbActivityDescExample tbActivityDescExample = new TbActivityDescExample();
                    tbActivityDescExample.createCriteria()
                            .andActivityIdEqualTo(reqClubActivity.getActivityId());
                    List<TbActivityDesc> tbActivityDescs =
                            tbActivityDescMapper.selectByExample(tbActivityDescExample);
                    if(null != tbActivityDescs && tbActivityDescs.size() > 0)
                    {
                        TbActivityDesc activityDesc = tbActivityDescs.get(0);
                        tbActivityDesc.setId(activityDesc.getId());
                        tbActivityDesc.setActivityId(activityDesc.getActivityId());
                    }
                }
            }
            logger.warn("tbActivityDesc:" + JSONObject.toJSONString(tbActivityDesc));
        }
        if(null != tbActivityMultimedias)
        {
            List<ActivityMedia> medias = reqClubActivity.getActivityMediaList();
            if(null != medias && medias.size() > 0)
            {
                for(ActivityMedia media : medias)
                {
                    TbActivityMultimedia tbActivityMultimedia = new TbActivityMultimedia();
                    tbActivityMultimedia.setMultimediaUrl(media.getImageUrl());
                    tbActivityMultimedia.setActivityId(tbActivity.getId());
                    //更新时关联原始ID
                    if(operate == 2)
                    {
                        tbActivityMultimedia.setActivityId(reqClubActivity.getActivityId());
                    }
                    tbActivityMultimedias.add(tbActivityMultimedia);
                }
            }
            logger.warn("tbActivityMultimedias:" + JSONObject.toJSONString(tbActivityMultimedias));
        }
    }

    private void convertActivityDbToResp(RespClubActivity respClubActivity,
                                         TbClubActivity tbClubActivity,
                                         TbActivity tbActivity,
                                         TbActivityPoster tbActivityPoster,
                                         TbActivityDesc tbActivityDesc,
                                         List<TbActivityMultimedia> tbActivityMultimedias)
    {
        if(null != tbActivityPoster)
        {
            RespActivityPoster respActivityPoster = new RespActivityPoster();
            respActivityPoster.setId(tbActivityPoster.getId());
            respActivityPoster.setClubId(tbActivityPoster.getClubId());
            respActivityPoster.setUrl(tbActivityPoster.getUrl());
            respClubActivity.setRespActivityPoster(respActivityPoster);
            logger.warn("respClubActivity:" + JSONObject.toJSONString(respClubActivity)
                    + "tbActivityPoster:" + JSONObject.toJSONString(tbActivityPoster));
        }
        if(null != tbActivityDesc)
        {
            ActivityDesc activityDesc = new ActivityDesc();
            activityDesc.setActivityId(tbActivityDesc.getActivityId());
            activityDesc.setId(tbActivityDesc.getId());
            activityDesc.setBodyDesc(tbActivityDesc.getBodyDesc());
            respClubActivity.setActivityDesc(activityDesc);
            logger.warn("respClubActivity:" + JSONObject.toJSONString(respClubActivity)
                    + "tbActivityDesc:" + JSONObject.toJSONString(tbActivityDesc));
        }
        if(null != tbActivityMultimedias && tbActivityMultimedias.size() > 0)
        {
            List<ActivityMedia> activityMedias = new ArrayList<ActivityMedia>();
            for(TbActivityMultimedia multimedia : tbActivityMultimedias)
            {
                ActivityMedia media = new ActivityMedia();
                media.setId(multimedia.getId());
                media.setImageUrl(multimedia.getMultimediaUrl());
                activityMedias.add(media);
            }
            respClubActivity.setActivityMediaList(activityMedias);
            logger.warn("respClubActivity:" + JSONObject.toJSONString(respClubActivity)
                    + "tbActivityMultimedia:" + JSONObject.toJSONString(tbActivityMultimedias));
        }
        if(null != tbClubActivity)
        {
            respClubActivity.setActivityId(tbClubActivity.getActivityId());
            respClubActivity.setLowestPrice(ActivityUtils.getLowestPrice(tbClubActivity));
            respClubActivity.setCurTime(new Date());
            respClubActivity.setUid(tbClubActivity.getUid());
            respClubActivity.setId(tbClubActivity.getActivityId());
            respClubActivity.setAaFee(tbClubActivity.getAaFee());
            respClubActivity.setActivityCycle(tbClubActivity.getActivityCycle());
            respClubActivity.setAaTotal(tbClubActivity.getAaTotal());
            respClubActivity.setCancelTimeLimit(tbClubActivity.getCancelTimeLimit());
            respClubActivity.setCityId(tbClubActivity.getCityId());

            TbClub club = tbClubMapper.selectByPrimaryKey(tbClubActivity.getClubId());
            if(null != club && club.getIsDelete() != 1) {
                respClubActivity.setClubId(tbClubActivity.getClubId());
                respClubActivity.setClubName(club.getClubName());
            }
            respClubActivity.setDistrictId(tbClubActivity.getDistrictId());
            respClubActivity.setFaceLevel(tbClubActivity.getFaceLevel());
            respClubActivity.setFeeType(tbClubActivity.getFeeType());
            respClubActivity.setFemaleFee(tbClubActivity.getFemaleFee());
            respClubActivity.setFemaleMemberFee(tbClubActivity.getFemaleMemberFee());
            respClubActivity.setIsCancelSignUp(tbClubActivity.getIsCancelSignUp());

            respClubActivity.setDistrictId(tbClubActivity.getDistrictId());
            respClubActivity.setIsSame(ActivityUtils.isSamePrice(tbClubActivity));
            respClubActivity.setJoinType(club.getJoinType());
            respClubActivity.setLat(tbClubActivity.getLat());
            respClubActivity.setLng(tbClubActivity.getLng());
            respClubActivity.setLogoUrl(club.getLogoUrl());
            respClubActivity.setMaleFee(tbClubActivity.getMaleFee());
            respClubActivity.setMaleMemberFee(tbClubActivity.getMaleMemberFee());
            respClubActivity.setMobile(tbClubActivity.getMobile());
            respClubActivity.setPlanner(tbClubActivity.getPlanner());
            respClubActivity.setSignUpMin(tbClubActivity.getSignUpMin());
            respClubActivity.setSignUpType(tbClubActivity.getSignUpType());
            respClubActivity.setWeekRange(tbClubActivity.getWeekRange());
            respClubActivity.setActivityType(tbClubActivity.getActivityType());
            respClubActivity.setCategoryId(tbClubActivity.getCategoryId());
            respClubActivity.setIsPrimeTime(tbClubActivity.getIsPrimeTime());
            respClubActivity.setCycleRange(tbClubActivity.getCycleRange());
            respClubActivity.setActivityRoot(tbClubActivity.getActivityRoot());
            if(null != tbClubActivity.getIsSettle())
            {
                respClubActivity.setIsSettle(tbClubActivity.getIsSettle().intValue());
            }
            logger.warn("respClubActivity:" + JSONObject.toJSONString(respClubActivity)
                    + "tbClubActivity:" + JSONObject.toJSONString(tbClubActivity));
            respClubActivity.setLowestPrice(ActivityUtils.getLowestPrice(tbClubActivity));
        }
        if(null != tbActivity)
        {
            respClubActivity.setPlaceAddress(tbActivity.getPlaceAddress());
            respClubActivity.setLimitNum(tbActivity.getLimitNum());
            respClubActivity.setPosterPicId(tbActivity.getPosterPicId());
            respClubActivity.setAlreadySignTotalNum(tbActivity.getAlreadySignTotalNum());
            respClubActivity.setEndTime(tbActivity.getEndTime());
            respClubActivity.setGroupId(tbActivity.getGroupId());
            respClubActivity.setName(tbActivity.getName());
            respClubActivity.setPlaceId(tbActivity.getPlaceId());
            respClubActivity.setSignStartTime(tbActivity.getSignStartTime());
            respClubActivity.setSignEndTime(tbActivity.getSignEndTime());
            respClubActivity.setStartTime(tbActivity.getStartTime());
            respClubActivity.setStatus(tbActivity.getStatus());
            respClubActivity.setRequireField(tbActivity.getRequireField());
            logger.warn("respClubActivity:" + JSONObject.toJSONString(respClubActivity)
                    + "tbActivity:" + JSONObject.toJSONString(tbActivity));
        }
        activitySupportService.getActivityPlace(respClubActivity);
    }

    public Map<Integer, Integer> createActivityFromExist(List<Integer> rootIds)
    {
        TbActivityExample activityExample = new TbActivityExample();
        activityExample.createCriteria().andIdIn(rootIds);
        List<TbActivity> activities = tbActivityMapper.selectByExample(activityExample);
        logger.warn("查询符合条件的List结果：" + JSONObject.toJSONString(activities));
        if(null == activities && activities.size() == 0)
        {
            return null;
        }
        Map<Integer, Integer> idMap = new HashMap<Integer, Integer>();
        for (TbActivity tbActivity : activities)
        {
            if(tbActivity.getStatus().equals(Constants.BYTE_TWO))
            {
                logger.warn("根活动已经取消，不循环这个活动：" + tbActivity.getId());
                continue;
            }
            Date oldStartTime = tbActivity.getEndTime();
            int oldId = tbActivity.getId();
            logger.warn("开始插入一条新的日循环活动，根活动ID：" + tbActivity.getId());

            TbClubActivityExample clubActivityExample = new TbClubActivityExample();
            clubActivityExample.createCriteria().andActivityIdEqualTo(tbActivity.getId());
            List<TbClubActivity> tbClubActivities =
                    tbClubActivityMapper.selectByExample(clubActivityExample);
            if(null == tbClubActivities ||  tbClubActivities.size() != 1)
            {
                logger.warn("脏数据周期活动：" + oldId);
                continue;
            }
            TbClubActivity tbClubActivity = tbClubActivities.get(0);
            int oldClubActivityId = tbClubActivity.getId();
            Byte weekRange = tbClubActivity.getWeekRange();
            Byte newRange = null;
            String cycleRange = tbClubActivity.getCycleRange();
            String[] cycles = cycleRange.split(",");
            Map<String, Object> queryMap = new HashMap<String, Object>();
            queryMap.put("activityRoot", oldId);
            queryMap.put("startTime", DateUtils.getTargetTimesmorning(oldStartTime));
            int cycleCount = clubActivityCRUDMapper.countCycleRangeEffect(queryMap);
            if(cycleCount == 0)
            {
                logger.warn("脏数据周期活动：" + oldId);
                continue;
            }
            int cycleLength = cycles.length;
            //新的周期
            int newCylceIndex = cycleCount%cycleLength;
            //需要向后移动位数
            for(int i = 0; i < cycleLength; i++)
            {
                if(Byte.valueOf(cycles[i]).equals(weekRange))
                {
                    newCylceIndex = (newCylceIndex + i)%cycleLength;
                }
            }
            newRange = Byte.parseByte(cycles[newCylceIndex]);
            //新的周期距离现在第几周
            Double count = Math.floor((double) cycleCount/cycleLength);
            //新的周期所在周的周几
            logger.warn("重定位新时间：" + newRange + ",距离多少周：" + count);
            if(newRange.intValue() < weekRange.intValue())
            {
                count = count + 1;
            }
            logger.warn("由于新周期在老周期的前面，距离周期改为：" + count);
            tbActivity.setStartTime(DateUtils.getRecentlyDateByWeek(
                    tbActivity.getStartTime(), newRange, count.intValue()));
            tbActivity.setEndTime(DateUtils.getRecentlyDateByWeek(
                    tbActivity.getEndTime(), newRange, count.intValue()));
            tbActivity.setSignStartTime(new Date());
            tbActivity.setSignEndTime(DateUtils.getRecentlyDateByWeek(
                    tbActivity.getSignEndTime(), newRange, count.intValue()));

            //活动表重新插入
            tbActivity.setId(null);
            tbActivity.setAlreadyLockSignTotalNum(null);
            tbActivity.setAlreadySignTotalNum(null);
            tbActivity.setCreateTime(null);
            tbActivity.setUpdateTime(null);
            TbActivityPoster poster =
                    tbActivityPosterMapper.selectByPrimaryKey(tbActivity.getPosterPicId());
            tbActivity.setGroupId(activitySupportService.createGroup(tbActivity.getName(),
                    tbClubActivity.getUid(), poster.getUrl()));
            tbActivity.setStatus(Constants.BYTE_ZERO);
            int activityCount = tbActivityMapper.insertSelective(tbActivity);
            if(activityCount == 0)
            {
                throw new BizException("create activity failed, oldActivityId:" + oldId);
            }
            int newId = tbActivity.getId();
            if(newId <= 0)
            {
                continue;
            }
            //活动描述重新插入
            TbActivityDescExample descExample = new TbActivityDescExample();
            descExample.createCriteria().andActivityIdEqualTo(oldId);
            List<TbActivityDesc> descs = tbActivityDescMapper.selectByExample(descExample);
            if(null == descs || descs.size() == 0)
            {
                continue;
            }
            TbActivityDesc tbActivityDesc = descs.get(0);
            tbActivityDesc.setActivityId(newId);
            tbActivityDesc.setId(null);
            tbActivityDesc.setCreateTime(null);
            tbActivityDesc.setUpdateTime(null);
            tbActivityDescMapper.insertSelective(tbActivityDesc);
            int desCount = this.tbActivityDescMapper.insertSelective(tbActivityDesc);
            if(desCount == 0)
            {
                throw new BizException("create activityDesc failed, oldActivityId:" + oldId);
            }
            //俱乐部活动表重新插入
            tbClubActivity.setActivityId(newId);
            tbClubActivity.setId(null);
            tbClubActivity.setIsFirst(null);
            tbClubActivity.setIsSettle(null);
            tbClubActivity.setIsSearch(null);
            tbClubActivity.setCreateTime(null);
            tbClubActivity.setUpdateTime(null);
            tbClubActivity.setIsRecommend(null);
            tbClubActivity.setActivityStatus(0f);
            tbClubActivity.setSignUpMin(0);
            tbClubActivity.setActivityRoot(oldId);
            tbClubActivity.setWeekRange(newRange);
            int clubActivityCount = tbClubActivityMapper.insertSelective(tbClubActivity);
            if(clubActivityCount == 0)
            {
                throw new BizException("create clubActivity failed, oldActivityId:" + oldId);
            }

            idMap.put(oldId, newId);
            TbActivityMultimediaExample multimediaExample = new TbActivityMultimediaExample();
            multimediaExample.createCriteria().andActivityIdEqualTo(oldId)
                    .andIsDeleteEqualTo(false);
            List<TbActivityMultimedia> multimedias =
                    tbActivityMultimediaMapper.selectByExample(multimediaExample);
            if(null != multimedias && multimedias.size() > 0)
            {
                for (TbActivityMultimedia activityMedia : multimedias)
                {
                    activityMedia.setCreateTime(null);
                    activityMedia.setUpdateTime(null);
                    activityMedia.setActivityId(newId);
                }
                int mulcount = clubActivityCRUDMapper.batchInsertMedia(multimedias);
                if(mulcount == 0)
                {
                    throw new BizException("create multimedia failed, oldActivityId:" + oldId);
                }
            }
            logger.warn("创建完周期活动，开始执行后续任务:" + newId);

            logger.warn("更新原始俱乐部周期活动，原始活动ID：" + oldId);
            TbClubActivity updateClubActivity = new TbClubActivity();
            updateClubActivity.setIsSearch(Constants.BYTE_ONE);
            TbClubActivityExample updateExample = new TbClubActivityExample();
            updateExample.createCriteria().andActivityRootEqualTo(oldId)
                    .andIsDeleteEqualTo(Constants.BYTE_ZERO).andActivityStatusIn(Arrays.asList(2f,3f));
            int updateCount = tbClubActivityMapper.updateByExampleSelective(updateClubActivity, updateExample);
            logger.warn("更新结束，更新数量:" + updateCount);
            RespClubActivity respClubActivity = selectClubActivityById(newId);
            activitySupportService.afterCreateWeekRange(respClubActivity);
        }
        return idMap;
    }

    public byte isCollect(Integer activityId, Integer uid) {
        if (uid == null) {
            return 0;
        }
        ReqUserCollectQuery reqUserCollect = new ReqUserCollectQuery();
        reqUserCollect.setSystemCode(UserCenterConstants.SystemCode.SYSTEM_ACTIVITY);
        reqUserCollect.setBusinessCode(UserCenterConstants.BusinessCode.BUSINESS_CLUB_ACTIVITY_COLLECT);
        reqUserCollect.setUserId(uid);
        reqUserCollect.setBusinessId(activityId);
        APIResponse<Boolean> apiResponse = userCollectServiceFacade.isUserCollect(reqUserCollect);
        Boolean result = apiResponse.getData();//false 未收藏 true收藏
        if (!result) {
            return Constants.BYTE_ONE;//是否收藏 0 未收藏 1 已收藏
        } else {
            return Constants.BYTE_ZERO;//是否收藏 0 未收藏 1 已收藏
        }

    }

    public PageObj<List<RespClubActivity>> queryClubActivityListAfterWeek(ReqClubActivityCondition reqClubActivityCondition)
    {
        List<RespClubActivity> list = new ArrayList<RespClubActivity>();
        Date weekStartTime = new Date();
        Calendar cal = Calendar.getInstance(Locale.CHINA);
        cal.setTime(weekStartTime);
        cal.add(Calendar.DAY_OF_WEEK, 7);
        Map<String, Object> map = Maps.newHashMap();
        map.put("clubId", reqClubActivityCondition.getClubId());
        map.put("fromStartTime", weekStartTime);
        map.put("toEndTime", cal.getTime());
        int count = clubActivityCRUDMapper.countClubActivityListByFree(map);
        if(count <= 0)
        {
            return PageObj.create(count, reqClubActivityCondition.getPageNum(),
                    reqClubActivityCondition.getPageSize(), list);
        }
        Limit limit = Limit.buildLimit(reqClubActivityCondition.getPageNum(),
                reqClubActivityCondition.getPageSize());
        map.put("pageStart", limit.getStart());
        map.put("pageSize", limit.getSize());
        list = clubActivityCRUDMapper.queryClubActivityListByFree(map);
        activitySupportService.getActivityPlaces(list, null, null);
        if(CollectionUtils.isEmpty(list))
        {
            return PageObj.create(count, reqClubActivityCondition.getPageNum(),
                    reqClubActivityCondition.getPageSize(), list);
        }
        return PageObj.create(count, reqClubActivityCondition.getPageNum(),
                reqClubActivityCondition.getPageSize(), list);
    }

}
